import Vue from 'vue';

// 格式化日期
Vue.prototype.formatTime = time => {
    //日期转化为例如...2018年1月12日 格式
    const date = new Date(time);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};
/* Vue.prototype.number_format = (num,cent,isThousand)=>{
    num = num.toString().replace(/\$|\,/g,'');  
    if(isNaN(num))//检查传入数值为数值类型.  
     num = "0";  
    if(isNaN(cent))//确保传入小数位为数值型数值.  
    cent = 0;  
    cent = parseInt(cent);  
    cent = Math.abs(cent);//求出小数位数,确保为正整数.  
    if(isNaN(isThousand))//确保传入是否需要千分位为数值类型.  
    isThousand = 0;  
    isThousand = parseInt(isThousand);  
    if(isThousand < 0)  
    isThousand = 0;  
    if(isThousand >=1) //确保传入的数值只为0或1  
    isThousand = 1;  
    sign = (num == (num = Math.abs(num)));//获取符号(正/负数)  
    //Math.floor:返回小于等于其数值参数的最大整数  
    num = Math.floor(num*Math.pow(10,cent)+0.50000000001);//把指定的小数位先转换成整数.多余的小数位四舍五入.  
    cents = num%Math.pow(10,cent); //求出小数位数值.  
    num = Math.floor(num/Math.pow(10,cent)).toString();//求出整数位数值.  
    cents = cents.toString();//把小数位转换成字符串,以便求小数位长度.  
    while(cents.length<cent){//补足小数位到指定的位数.  
    cents = "0" + cents;  
    }  
    if(isThousand == 0) //不需要千分位符.  
    return (((sign)?'':'-') + num + '.' + cents);  
    //对整数部分进行千分位格式化.  
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)  
    num = num.substring(0,num.length-(4*i+3))+','+  
    num.substring(num.length-(4*i+3));  
    return (((sign)?'':'-') + num + '.' + cents);  
}; */

//格式化金额 三位加逗号处理保留两位置小数
Vue.prototype.roundFun = (numberRound,roundDigit) => {
    if   (numberRound>=0){
        var   tempNumber   =   parseInt((numberRound   *   Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit);
        return   tempNumber;
        } else{
        numberRound1=-numberRound;
        var   tempNumber   =   parseInt((numberRound1   *   Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit);
        return   -tempNumber;
        }
}
Vue.prototype.isString = o =>{ //是否字符串  
    return Object.prototype.toString.call(o).slice(8, -1) === 'String'  
};
Vue.prototype.isNumber = o =>{ //是否数字  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Number'  
};
Vue.prototype.isObj = o =>{ //是否对象  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Object'  
};
Vue.prototype.isArray = o =>{ //是否数组  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Array'  
}  
Vue.prototype.isDate = o =>{ //是否时间  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Date'  
}  
Vue.prototype.isBoolean = o =>{ //是否boolean  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'  
}  
Vue.prototype.isFunction = o =>{ //是否函数  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Function'  
}  
Vue.prototype.isNull = o =>{ //是否为null  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Null'  
}  
Vue.prototype.isUndefined = o =>{ //是否undefined  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'  
}
Vue
Vue.prototype.isFalse = o =>{  //是否一切非值 
    if (!o || o === 'null' || o === 'undefined' || o === 'false' || o === 'NaN' || o === '') return true 
        return false  
} 
 
Vue.prototype.isTrue = o =>{  //跟上面相反 
    return !this.isFalse(o)  
}
Vue.prototype.isEmptyObject = e =>{ //是否为空
	var t;
	for (t in e)
		return !1;
	return !0
}
Vue.prototype.browserType = () =>{  //判断是什么浏览器
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器  
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器  
    var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器  
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器  
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器  
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器  
    if (isIE) {  
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");  
        reIE.test(userAgent);  
        var fIEVersion = parseFloat(RegExp["$1"]);  
        if(fIEVersion == 7) return "IE7"  
        else if(fIEVersion == 8) return "IE8";  
        else if(fIEVersion == 9) return "IE9";  
        else if(fIEVersion == 10) return "IE10";  
        else if(fIEVersion == 11) return "IE11";  
        else return "IE7以下"//IE版本过低  
    } 
 
    if (isFF) return "FF";  
    if (isOpera) return "Opera";  
    if (isEdge) return "Edge";  
    if (isSafari) return "Safari";  
    if (isChrome) return "Chrome";  
};
Vue.prototype.checkStr = (str, type) => {  
    switch (type) {  
        case 'phone':   //手机号码
            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);  
        case 'tel':     //座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);  
        case 'card':    //身份证
            return /^\d{15}|\d{18}$/.test(str);  
        case 'pwd':     //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
            return /^[a-zA-Z]\w{5,17}$/.test(str)  
        case 'postal':  //邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);  
        case 'QQ':      //QQ号
            return /^[1-9][0-9]{4,9}$/.test(str); 
        case 'email':   //邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);  
        case 'money':   //金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);  
        case 'URL':     //网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)  
        case 'IP':      //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);  
        case 'date':    //日期时间
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)  
        case 'number':  //数字
            return /^[0-9]$/.test(str);  
        case 'english': //英文
            return /^[a-zA-Z]+$/.test(str);  
        case 'chinese': //中文
            return /^[\u4E00-\u9FA5]+$/.test(str);  
        case 'lower':   //小写
            return /^[a-z]+$/.test(str);  
        case 'upper':   //大写
            return /^[A-Z]+$/.test(str);  
        case 'HTML':    //HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);  
        default:  
            return true;  
    }  
};
Vue.prototype.unique = (arr) => {  /* 去重 */
    if ( Array.hasOwnProperty('from') ) {  
        return Array.from(new Set(arr));  
    }else{  
        var n = {},r=[];   
        for(var i = 0; i < arr.length; i++){  
            if (!n[arr[i]]){  
                n[arr[i]] = true;   
                r.push(arr[i]);  
            }  
        }  
        return r;  
    }  
};
Vue.prototype.max = (arr) => {  /* 最大值 */ 
    return Math.max.apply(null, arr);  
};
Vue.prototype.min = (arr) => {  /* 最小值 */
    return Math.min.apply(null, arr);  
};
Vue.prototype.isEven = num => num % 2 === 0;    /* Even or odd number(判断奇偶数) */
Vue.prototype.getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);  /* (获取两个日期之间相差的天数) */
//getDaysDiffBetweenDates(new Date("2017-11-13"), new Date("2017-12-13")) -> 30
Vue.prototype.reverseString = str => [...str].reverse().join(''); /* 使用数组解构和 Array.reverse() 来反转字符串中字符的顺序。使用 join('')合并字符串。 */

Vue.prototype.toFixedOriginFn=function(num,n){
    if (Number.isInteger(num)) {
        return num
    }
    let isNegative=false;
    if(num<0){
        isNegative=true;
        num=Math.abs(num);  
    }
    let result = num.toString();
    const arr = result.split('.');
    const integer = arr[0];
    const decimal = arr[1];
    result = integer + '.' + decimal.substr(0, n);
    const last = decimal.substr(n, 1);
    // 四舍五入，转换为整数再处理，避免浮点数精度的损失
    if (parseInt(last, 10) >= 5) {
        const x = Math.pow(10, n);
        result = ((parseFloat(result) * x) + 1) / x;
        result = result.toFixed(n);
    }
    return isNegative?-1*result:result;  
}

Vue.prototype.doToFixedFn=function(num){//输入框四舍五入到小数点后两位（没有属性）
    if (!this.isFalse(this[num])) {
        //this[num]=Math.round(Number(this[num])*100)/100;
        let target=Number(this[num]);
        this[num]=this.toFixedOriginFn(target,2);
    }
}

Vue.prototype.doToFixed=function(num,attr1,attr2){//输入框四舍五入到小数点后两位（有属性）
    if (this.isUndefined(attr2)) {//有attr1,没有attr2
      if (!this.isFalse(num[attr1])) {
        //num[attr1]=Math.round(Number(num[attr1])*100)/100;
        let target=Number(num[attr1]);
        num[attr1]=this.toFixedOriginFn(target,2);
      }  
    }else{////有attr1,有attr2
      if (!this.isFalse(num[attr1][attr2])) {   
        //num[attr1][attr2]=Math.round(Number(num[attr1][attr2])*100)/100
        let target=Number(num[attr1][attr2]);
        num[attr1][attr2]=this.toFixedOriginFn(target,2);
      }
    }
}

Vue.prototype.onlyNumBasicFn=function(num){//限制输入框基本类型只能输入数字
    if (!this.isFalse(this[num])) {
      this[num]=this[num].toString().replace(/[^\-?\d.]/g,'');
    }
}

Vue.prototype.onlyNumObjFn=function(num,attr1,attr2){//限制输入框的对象只能输入数字
    if (this.isUndefined(attr2)) {//有attr1,没有attr2
      if (!this.isFalse(num[attr1])) {
        num[attr1]=num[attr1].toString().replace(/[^\-?\d.]/g,'');
      }  
    }else{////有attr1,有attr2
      if (!this.isFalse(num[attr1][attr2])) {   
        num[attr1][attr2]=num[attr1][attr2].toString().replace(/[^\-?\d.]/g,'');
      }
    }
}

Vue.prototype.getMayHaveCommunicationFn=function(params){
    return new Promise(function(resolve,reject){
      axios.get('getMayHaveCommuniState',params).then(res=>{
        if (res=="True") {
          resolve()
        }else{
          reject()
        }
      }).catch(err=>{
        console.log(err,"err")
      });
    })
}
